﻿using Biz.Buffer;
using Biz.EF.Gateway.Monitor;
using Biz.EF.Platform.SG;
using Biz.Process;
using Hjt212Parser;
using log4net;
using System;
using System.Data.Entity.Validation;
using System.Linq;
using System.Security.Cryptography;
using System.ServiceProcess;
using System.Threading;

namespace Biz
{
    public partial class BizProcessor : ServiceBase
    {
        private readonly ILog _log = LogManager.GetLogger(typeof(BizProcessor));
        private readonly int _milliSeconds = 10;

        public BizProcessor()
        {
            InitializeComponent();
        }
        //test
        public void Main()
        {
            OnStart(null);

        }
        protected override void OnStart(string[] args)
        {
            //启动各路线程
            new Thread(ProcessData) { IsBackground = true }.Start();
            new Thread(SendAlarm) { IsBackground = true }.Start();
            _log.Info("各路线程启动完成...");
        }
        protected override void OnStop()
        {
            _log.Info("The processor Stopped!");
            Environment.Exit(0);
        }
        private void ProcessData(object state)
        {
            while (true)
            {
                try
                {
                    using (var gCtx = new GatewayMonitorContext())
                    {
                        var flag = ProcessFlag.NotProcessed.ToString();
                        var items =
                            gCtx.received_msg.Where(t => t.is_length_right)
                                .Where(t => t.processed_flag.Equals(flag))
                                .OrderBy(t => t.datatime)
                                .Take(1000)
                                .ToList();
                        foreach (var item in items)
                        {
                            _log.Info(item.received_string);
                            item.processed_flag = ProcessFlag.ProcessingFinished.ToString();
                            if(string.IsNullOrWhiteSpace(item.cn)) continue;
                            switch (item.cn)
                            {
                                case "2011":
                                case "G011":
                                    Processor2011.ProcessToMonitorTable(item.received_string);
                                    Processor2011.ProcessToWechatSingleTablePerEnterprise(item.received_string);
                                    Processor2011.ProcessToCommonTable(item.received_string);

                                    ProcessorAlarm.ProcessOverflow(item.received_string);
                                    ProcessorAlarm.ProcessToNewConcentration(item.received_string);
                                  
                                 
                                    break;
                                case "2051":
                                case "G051":
                                    Processor2051.ProcessToMonitorTable(item.received_string);
                                    Processor2051.ProcessToWechatSingleTablePerEnterprise(item.received_string);
                                    Processor2051.ProcessToCommonTable(item.received_string);

                                
                                    break;
                                case "2061":
                                case "G061":
                                    Processor2061.ProcessToMonitorTable(item.received_string);
                                    Processor2061.ProcessToWechatSingleTablePerEnterprise(item.received_string);
                                    Processor2061.ProcessToCommonTable(item.received_string);

                                    Processor2061.SumToMonitorDayFromHour(item.received_string);
                                    Processor2061.SumToMonitorMonthFromHour(item.received_string);
                                    Processor2061.SumToMonitorYearFromHour(item.received_string);

                                    break;
                                case "2031":
                                case "G031":
                                    Processor2031.ProcessToMonitorTable(item.received_string);
                                    Processor2031.ProcessToWechatSingleTablePerEnterprise(item.received_string);
                                    Processor2031.ProcessToCommonTable(item.received_string);

                                    Processor2031.SumToMonthFromDay(item.received_string);
                                    Processor2031.SumToYearFromDay(item.received_string);
                                    break;
                            }

                            if (item.cn.Contains("000"))
                            {
                                ProcessorStatus.ProcessOffline(item.received_string);
                                ProcessorAlarm.ProcessOffline(item.received_string);
                            }
                            else
                            {
                                ProcessorAlarm.ProcessOnline(item.received_string);
                            }
                          
                        }
                        gCtx.SaveChanges();
                    }
                }
                catch (DbEntityValidationException dbEx)
                {
                    foreach (var validationErrors in dbEx.EntityValidationErrors)
                    {
                        foreach (var validationError in validationErrors.ValidationErrors)
                        {

                            _log.Error(string.Format("Class: {0}, Property: {1}, Error: {2}", validationErrors.Entry.Entity.GetType().FullName,
                                 validationError.PropertyName,
                                 validationError.ErrorMessage));
                        }
                    }
                }
                catch (Exception ex)
                {
                    _log.Error(ex);
                }
                finally
                {
                    ThreadUtil.Sleep(_milliSeconds);
                }
            }
            // ReSharper disable once FunctionNeverReturns
        }

        private void SendAlarm(object state)
        {
            while (true)
            {
                try
                {
                    ProcessorAlarm.ProcessConstant();
                    using (var gCtx = new PlatformXpfContext())
                    {
                        var begin = DateTime.Now.AddMinutes(-60);
                        var alarmType = CommonInformation.GetAlarmTypeByCode("offline");
                        if (alarmType == null)
                        {
                            return;
                        }

                        var items =
                            gCtx.报警记录.Where(t => !t.是否发送).Where(t => t.报警异常数据类型ID == alarmType.ID).Where(t => t.报警时间 <= begin).OrderBy(t => t.报警时间).Take(1000);
                        foreach (var item in items)
                        {
                            _log.Info(item.内容);
                            item.是否发送 = true;
                            QqMail.Send(item.内容);
                        }
                        gCtx.SaveChanges();

                        items =
                            gCtx.报警记录.Where(t => !t.是否发送).Where(t => t.报警异常数据类型ID != alarmType.ID).OrderBy(t => t.报警时间).Take(1000);
                        foreach (var item in items)
                        {
                            _log.Info(item.内容);
                            item.是否发送 = true;
                            QqMail.Send(item.内容);
                        }
                        gCtx.SaveChanges();
                    }
                }
                catch (Exception ex)
                {
                    _log.Error(ex);
                }
                finally
                {
                    ThreadUtil.Sleep(1 * 60 * 1000);
                }
            }
            // ReSharper disable once FunctionNeverReturns
        }


    }
}
